package xp2p.inter.client;

import java.io.IOException;
import java.io.Serializable;

public class ClientRetryer
{
	private ClientProvider provider;
	private Client client;
	
	public ClientRetryer(int port)
	{
		provider = new ClientProvider(port);
	}
	
	public void send(Serializable message) throws InnerException
	{
		for (int i =0; i < Statics.MaxFailures; i++)
		{
			try
			{
				client = provider.getClient();
				client.send(message);
				return;
			} catch (IOException e)
			{
				provider.close();
				e.printStackTrace();
			} catch (ClassNotFoundException e)
			{				
				provider.close();
				e.printStackTrace();
			}
		}
		throw new InnerException();
	}

	public Serializable request(Serializable message) throws InnerException
	{
		for (int i =0; i < Statics.MaxFailures; i++)
		{
			try
			{
				client = provider.getClient();
				return client.request(message);				
			} catch (IOException e)
			{
				provider.close();
				e.printStackTrace();				
			} catch (ClassNotFoundException e)
			{				
				provider.close();
				e.printStackTrace();
				
			}
		}		
		throw new InnerException();
	}
	
	public void close()
	{
		if (!client.wasClosed())
		{
			client.close();
		}
		provider.close();
	}
}
